package com.jml.statement;

import com.jml.annotation.Select;
import com.jml.session.Configuration;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;


public class MappedStatement {

    private Configuration configuration;
    //sql语句
    private String sqlValue;
    //sql语句类型
    private Annotation sqlType;
    //传递参数
    private Object[] args;

    private Annotation[] annotations;

    public MappedStatement(Method method, Object[] args) {
        this.resultType = method.getReturnType();
        this.args = args;
        annotations = method.getAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            if (annotations[i] instanceof Select) {
                this.sqlType = annotations[i];
            }/*else if(annotations[i] instanceof Update){
                this.sqlType = annotations[i];
            }*/
        }

        getSqlTypeValue(this.sqlType);

    }

    public void getSqlTypeValue(Annotation sqlType) {
        if (sqlType instanceof Select) {
            Select select = (Select) sqlType;
            sqlValue = select.value();
        }
    }

    public Select getSelectAnnotation() {
        if (sqlType instanceof Select) {
            Select select = (Select) sqlType;
            return select;
        }
        return null;
    }

    //key是sql+参数值+返回类型拼接而成
    public String getMappedStatementKey() {
        String mappedStatementKey = sqlValue + arrayToString() + resultType.toString();
        System.out.println(mappedStatementKey);
        return mappedStatementKey;
    }

    public String arrayToString() {
        String str = "";
        for (int i = 0; i < args.length; i++) {
            Object obj = (Object) args[i];
            str += obj + "";
        }
        return str;
    }


    /**
     * 返回类型
     */
    private Class<?> resultType;

    public String getSqlValue() {
        return sqlValue;
    }

    public Annotation getSqlType() {
        return sqlType;
    }

    public Class<?> getResultType() {
        return resultType;
    }

    public void setSqlValue(String sqlValue) {
        this.sqlValue = sqlValue;
    }

    public void setSqlType(Annotation sqlType) {
        this.sqlType = sqlType;
    }

    public void setResultType(Class<?> resultType) {
        this.resultType = resultType;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public Object[] getArgs() {
        return args;
    }

    @Override
    public String toString() {
        return "MappedStatement{" +
                "configuration=" + configuration +
                ", sqlValue='" + sqlValue + '\'' +
                ", sqlType=" + sqlType +
                ", args=" + Arrays.toString(args) +
                ", resultType=" + resultType +
                '}';
    }
}
